<template>
  <!-- 最外层容器 -->
  <div class="user-message-letter-container">
    <!-- 顶部清除浮动线 -->
    <div class="line-top"></div>
    <!-- 中间整个容器 -->
    <div class="container-in">
      <!-- 右则边栏-导航 -->
      <div class="aside"></div>
      <!-- /右则边栏 结束 -->
      <!-- 左边内容容器 开始 -->
      <div class="main">
        <!-- 顶部头像区域 -->
        <div class="avatar-box">
          <div class="avatar-div">
            <nuxt-link :to="'/user/'+userId"><img :src="avatar" alt=""></nuxt-link>
            <nuxt-link :to="'/user/'+userId"><b>{{ username }}</b></nuxt-link>
          </div>
          <div class="m-n-box">
            <!-- 通知图标、总数 -->
            <nuxt-link :to="'/user/notice/'+userId" class="letter-a">
              <h1 class="el-icon-message-solid"></h1> <span style="color: red;">{{ allMessageUnreadCount }}</span>
            </nuxt-link>
            <!-- 私信图标、总数 -->
            <nuxt-link :to="'/user/message/'+userId" class="letter-a">
              <h1 class="el-icon-message" style="color: red;"></h1> <span style="color: red;">{{
                allMessageUnreadCount
              }}</span></nuxt-link>
          </div>
        </div>
        <div class="letter-box">
          <h1>私信详情</h1>
          <!-- 私信目标用户/发送私信图标按钮 -->
          <div class="target-box">
            <div style="display: flex;justify-content: space-between;align-items: center;margin: 20px 0 20px;">
              <div style="display: flex;">
                <h3>来自 </h3>
                <nuxt-link :to="'/user/'+target.id">
                  <h3 style="color: black;font-weight: bold;">&nbsp;<i class="el-icon-user-solid"/>
                    {{ target.username }} &nbsp;</h3>
                </nuxt-link>
                <h3> 的私信</h3>
              </div>
              <!-- 打开发送私信窗口 -->
              <span class="el-icon-edit-outline add" @click="show"></span>
            </div>
          </div>
          <!-- 新增发送私信 -->
          <el-card class="box-card send-card" v-show="sendLetterBox">
            <div slot="header" class="clearfix">
              <span><i class="el-icon-message"/> 发送私信</span>
            </div>
            <div class="text item">
              <el-form :model="formData" :rules="rules" ref="ruleForm" label-width="100px" label-position="top">
                <el-form-item label="" prop="username">
                  <p style="font-size: 14px;"> 发信人：{{ username }}</p>
                  <el-input v-model="formData.username" maxlength="20" clearable show-word-limit
                            placeholder="请输入收信人名称"></el-input>
                </el-form-item>
                <el-form-item label="" prop="content">
                  <el-input type="textarea" v-model="formData.content" maxlength="500" clearable
                            @keyup.enter.native="addMessage('ruleForm')" placeholder="请输入私信内容"></el-input>
                </el-form-item>
                <el-form-item align="right">
                  <el-button @click="resetForm('ruleForm')">重置</el-button>
                  <el-button @click="cancel('ruleForm')">取消</el-button>
                  <el-button type="primary" @click="addMessage('ruleForm')">立即发送</el-button>
                </el-form-item>
              </el-form>
            </div>
          </el-card>
          <ul>
            <!-- 私信详情列表 -->
            <li v-for="item in details" :key="item.id">
              <div class="box-card-div">
                <!-- 私信目标头像 -->
                <div>
                  <nuxt-link :to="'/user/'+item.fromUserId">
                    <img :src="item.fromAvatar" alt="">
                  </nuxt-link>
                </div>
                <div style="width: 100%;">
                  <div style="display: flex;justify-content: space-between;">
                    <nuxt-link :to="'/user/'+item.fromUserId"><b>{{ item.fromUsername }}</b></nuxt-link>
                    <div>
                      <!-- 打开回复私信按钮 -->
                      <el-button v-if="item.fromUserId !== userId" type="primary" plain size="mini" icon="el-icon-edit"
                                 circle @click="open(item.id)"/>
                      <!-- 举报私信 -->
                      <el-button v-if="item.fromUserId !== userId" type="primary" plain size="mini"
                                 icon="el-icon-wind-power" circle
                                 @click="openReport(item.id,item.fromUsername,item.content,item.fromUserId)"/>
                      <!-- 删除私信 -->
                      <el-button type="primary" plain size="mini" icon="el-icon-delete" circle
                                 @click="remove(item.id)"/>
                    </div>
                  </div>
                  <p class="content">{{ item.content }}</p>
                  <p class="time">发送于 {{ getDateFormat(item.createTime) }}</p>
                </div>
              </div>
              <!-- 新增回复私信表单 -->
              <el-card class="box-card send-card" v-show="replyLetterIndex===item.id">
                <div class="text item">
                  <el-form :model="formData" label-width="100px" label-position="top">
                    <div style="font-size: 16px;margin: 20px 0;"><b> 回复 <i class="el-icon-user-solid"/>
                      {{ target.username }} </b></div>
                    <el-form-item label="" prop="content">
                      <el-input type="textarea" v-model="formData.content" maxlength="500" clearable
                                :placeholder="'@ '+ target.username + ' 请输入私信内容...'"
                                @keyup.enter.native="replyMessage(target.username ,formData.content,item.id)"></el-input>
                    </el-form-item>
                    <el-form-item align="right">
                      <el-button @click="close(item.id)">取消</el-button>
                      <el-button type="primary" @click="replyMessage(target.username ,formData.content,item.id)">立即发送
                      </el-button>
                    </el-form-item>
                  </el-form>
                </div>
              </el-card>
            </li>
            <!-- 分页组件 -->
            <template v-if="total>10">
              <!-- md 分页组件 开始 -->
              <el-pagination
                class="sm-hidden"
                background
                @current-change="handleCurrentChange"
                :current-page="current"
                :page-size="size"
                layout="total, prev, pager, next, jumper"
                :total="Number(total)">
              </el-pagination>
              <!-- sm 分页组件 开始 -->
              <el-pagination
                class="md-hidden"
                small
                background
                @current-change="handleCurrentChange"
                :current-page="current"
                :page-size="size"
                layout="total,prev, pager, next"
                :total="Number(total)">
              </el-pagination>
            </template>
          </ul>
        </div>
      </div>
      <!-- /左边内容容器   -->
    </div>
    <!-- 举报私信窗口 -->
    <el-dialog
      :visible.sync="dialogVisible"
      :width='dialogWidth'
      :before-close="openOrCloseReport">
      <el-form
        ref="reportForm"
        :model="reportData"
        label-width="100px"
        label-position="top"
        status-icon>
        <h1><i class="el-icon-wind-power"/> 举报私信</h1>
        <el-divider></el-divider>
        <p>私信发送人：<b> {{ reportData.title }}</b></p>
        <el-divider></el-divider>
        <p>要举报的私信内容： <b>{{ reportData.content }}</b></p>
        <el-divider></el-divider>
        <el-form-item label="举报原因：" prop="reportType">
          <!-- 举报原因：(0 作品侵权；1 涉嫌违法；2 内容不雅；3 骚扰谩骂；4 虚假宣传；5 低质灌水；6 其它 ) -->
          <el-radio-group v-model="reportData.reportType" size="small">
            <el-radio-button :label="0">作品侵权</el-radio-button>
            <el-radio-button :label="1">涉嫌违法</el-radio-button>
            <el-radio-button :label="2">内容不雅</el-radio-button>
            <el-radio-button :label="3">骚扰谩骂</el-radio-button>
            <el-radio-button :label="4">广告欺诈</el-radio-button>
            <el-radio-button :label="5">低质灌水</el-radio-button>
            <el-radio-button :label="6">其它</el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="补充说明：" prop="description" class="i-input">
          <el-input type="textarea" :rows="3" v-model="reportData.description" maxlength="500" clearable
                    @keyup.enter.native="addReport('reportForm')"/>
        </el-form-item>
        <p class="p">站务会尽快处理您的举报，处理结果，请留意站内通知!</p>
        <p class="p">感谢您为共建文明社区付出!</p>
        <div class="btn">
          <el-button @click="resetForm('reportForm')">重置</el-button>
          <el-button @click="openOrCloseReport">取消</el-button>
          <el-button type="primary" @click="addReport('reportForm')">提交</el-button>
        </div>
      </el-form>
    </el-dialog>
    <!-- 底部清除浮动线 -->
    <div class="line-bottom"></div>
  </div>
</template>
<script>
import {dateFormat} from '@/utils/date' // 日期格式化

export default {
  name: "user-message-letter",
  // 引用中间件，拦截路由请求，判断是否已经身份认证
  middleware: 'auth',
  // 动态标题
  head() {
    return {
      title: '私信详情 - 经历网'
    }
  },
  async asyncData({app, store, route}) {
    // 认证登录用户信息
    const userId = store.state.userInfo && store.state.userInfo.id || 0
    const avatar = store.state.userInfo && store.state.userInfo.avatar || ''
    const username = store.state.userInfo && store.state.userInfo.username || ''
    // 分页列表
    const current = 1
    const size = 10
    const conversationId = route.query.id
    const {data: messageDetailsList} = await app.$getMessageDetailsByConversationId(current, size, conversationId)
    const details = messageDetailsList.records
    const total = messageDetailsList.total
    const target = messageDetailsList.target
    const allMessageUnreadCount = messageDetailsList.allMessageUnreadCount
    return {
      userId,
      avatar,
      username,
      current,
      size,
      conversationId,
      details,
      total,
      target,
      allMessageUnreadCount
    }
  },
  data() {
    return {
      // 新增私信窗口，默认不显示
      sendLetterBox: false,
      // 新增私信数据
      formData: {
        username: '',
        content: ''
      },
      // 新增私信表单校验
      rules: {
        username: [
          {required: true, message: '收信人名不能为空', trigger: 'blur'},
          {min: 1, max: 10, message: '长度在 1 到 20 个字符', trigger: 'blur'}
        ],
        content: [
          {required: true, message: '私信内容不能为空', trigger: 'blur'},
          {min: 1, max: 500, message: '长度在 1 到 500 个字符', trigger: 'blur'}
        ]
      },
      // 回复私信窗口(默认是关闭)
      replyLetterIndex: -1,
      // 举报私信
      // 动态改变弹窗的尺寸用
      dialogWidth: '0',
      dialogVisible: false,
      reportData: {
        title: '',
        entityId: null,
        entityUserId: '',
        entityType: '3',
        reportType: '',
        description: '',
        content: '',
      }
    }
  },
  methods: {
    // 新增举报私信
    async addReport() {
      if (this.reportData.reportType === '') {
        this.$message.error("请选择举报原因")
        return
      }
      await this.$addReport(this.reportData).then(response => {
        if (response.code === 200) {
          this.dialogVisible = !this.dialogVisible
          this.$message.success("举报私信成功")
        } else {
          this.$message.error(response.message)
        }
      });
    },
    // 打开举报窗口
    openReport(id, fromUsername, content, fromUserId) {
      this.reportData.entityId = id
      this.reportData.title = fromUsername
      this.reportData.content = content
      this.reportData.entityUserId = fromUserId
      this.dialogVisible = true
      const val = document.body.clientWidth;
      const def = 800 // 默认宽度
      if (val < def) {
        this.dialogWidth = '95%'
      } else {
        this.dialogWidth = def + 'px'
      }
    },
    // 关闭举报窗口
    openOrCloseReport() {
      this.dialogVisible = false
    },
    // 格式化日期时间
    getDateFormat(date) {
      return dateFormat(date)
    },
    // 刷新私信会话列表
    async fetchData() {
      if (this.conversationId === '') {
        window.location = '/message/' + this.userId;
      }
      const {data} = await this.$getMessageDetailsByConversationId(this.current, this.size, this.conversationId);
      this.details = data.records
      this.total = data.total
      this.target = data.target
      this.allMessageUnreadCount = data.allMessageUnreadCount
    },
    // 切换分页
    handleCurrentChange(current) {
      this.current = current
      this.fetchData()
    },
    // 显示发送私信窗口（新增）
    show() {
      this.formData.username = ''
      this.formData.content = ''
      this.sendLetterBox = !this.sendLetterBox
    },
    // 发送私信（新增私信）
    async addMessage(ruleForm) {
      this.$refs[ruleForm].validate(async (valid) => {
        if (valid) {
          await this.$addMessage(this.formData).then(response => {
            if (response.code === 200) {
              // 关闭窗口
              this.sendLetterBox = !this.sendLetterBox
              // 刷新列表数据
              this.fetchData()
              this.$message.success(response.message)
            } else {
              this.$message.error(response.message)
            }
          })
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    // 重置表单
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    // 取消
    cancel(formName) {
      // 关闭窗口
      this.sendLetterBox = !this.sendLetterBox
      this.$refs[formName].resetFields();
    },
    // 根据会话ID-批量删除私信
    remove(id) {
      this.$confirm('您确定要删除这条私信吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 发送删除请求
        this.$removeMessageById(id).then(response => {
          if (response.code === 200) {
            this.fetchData()
            this.$message.success(response.message)
          } else {
            this.$message.error(response.message)
          }
        })
      }).catch(() => {
        // 取消删除，什么也不做
      })
    },
    // 打开回复私信窗口
    open(id) {
      this.formData.content = ''
      this.replyLetterIndex = this.replyLetterIndex === id ? -1 : id;
    },
    // 取消回复私信
    close(id) {
      this.formData.content = ''
      this.replyLetterIndex = this.replyLetterIndex === id ? -1 : id;
    },
    // 回复私信
    replyMessage(username, content, id) {
      if (username === '') {
        this.$message.error('私信目标用户名不能为空')
        return
      }
      if (content === '') {
        this.$message.error('私信内容不能为空')
        return
      }
      if (content.length < 1 || content.length > 500) {
        this.$message.error('私信内容长度为 1 至 500 个字符')
        return
      }
      this.formData.username = username
      this.formData.content = content

      this.$addMessage(this.formData).then(response => {
        if (response.code === 200) {
          // 关闭窗口
          this.replyLetterIndex = this.replyLetterIndex === id ? -1 : id;
          // 刷新列表数据
          this.fetchData()
          this.$message.success(response.message)
        } else {
          this.$message.error(response.message)
        }
      })
    }

  }
}
</script>
<style lang="less" scoped>
.user-message-letter-container {
  min-height: 630px;
  background-color: #242424;

  .el-dialog .el-form {
    padding: 0 30px 20px;

    .p {
      text-align: center;
      font-size: 16px;
    }

    .btn {
      margin-top: 30px;
      text-align: right;
    }
  }

  // 页面左则容器、右则容器
  .main, .aside {
    border-radius: 4px;
  }

  .main {
    background: linear-gradient(to left, #e5e4e4, #e5e4e4, black);

    // 顶部大头像区
    .avatar-box {
      background-color: black;
      box-shadow: 0 0 20px 6px white;

      .avatar-div {
        display: flex;
        justify-content: center;
        padding-top: 20px;
        align-items: center;

        b {
          margin-left: 20px;
          color: #d9d7d7;
        }
      }

      // 通知私信图标
      .m-n-box {
        display: flex;
        align-items: center;
        justify-content: space-between;

        a {
          color: white;
        }
      }

      // 顶部头像
      img {
        width: 100px;
        height: 100px;
        border-radius: 50%;
        box-shadow: 0 0 20px 6px white;
        transition: all .4s ease-in-out;
        -webkit-transition: all .4s ease-in-out;
        object-fit: cover;
      }

      img:hover {
        transform: rotate(360deg);
        -webkit-transform: rotate(360deg);
      }
    }

    // 私信会话列表
    .letter-box {

      h1 {
        text-align: center;
      }

      // 发送私信窗口
      .send-card {
        clear: both;
        margin: 20px auto;
        box-shadow: 0 8px 20px rgba(0, 0, 0, 0.6);
      }

      // 发送私信图标
      .add {
        font-size: 30px;
        cursor: pointer;
        box-shadow: 0 0 20px 6px white;
      }

      // 来自xx的私信
      .target {
        font-size: 18px;
        color: white;
        box-shadow: 0 0 20px 6px white;
      }

      ul {
        margin: 0 auto 20px;
        padding: 20px 0;
        border-radius: 4px;
        background-color: #FFFFFF;
        box-shadow: 0 8px 20px rgba(0, 0, 0, 0.6);

        li {
          // 私信会话容器
          .box-card-div {
            display: flex;
            border-bottom: solid 1px #c8c9cb;
            background-color: #FFFFFF;

            // 私信内容
            .content {
              margin: 5px 0 10px;
              font-size: 16px;
            }

            .time {
              margin-bottom: 5px;
              font-size: 12px;
            }

            .count {
              font-size: 14px;
            }

            // 私信目标头像
            img {
              width: 50px;
              height: 50px;
              padding: 1px;
              border: #bbbec3 solid 1px;
              border-radius: 50%;
              box-shadow: 0 8px 20px rgba(0, 0, 0, 0.6);
              transition: all .4s ease-in-out;
              -webkit-transition: all .4s ease-in-out;
              object-fit: cover;
              margin-right: 20px;
            }

            img:hover {
              transform: rotate(360deg);
              -webkit-transform: rotate(360deg);
            }
          }
        }
      }
    }
  }
}

// md
@media screen and (min-width: 960px) {
  .user-message-letter-container {
    background-size: 100% 100%;

    .container-in {
      width: 80%;
      margin: 0 auto;
      padding-bottom: 26px;

      .main {
        float: left;
        width: 75%;
        margin-left: 26px;
        border-radius: 4px;

        // 顶部大头像区
        .avatar-box {

          .el-icon-message-solid {
            padding-left: 150px;
            color: white;
          }

          .letter-a {
            padding-right: 150px;
            color: white;
          }
        }

        .box-card {
          width: 70%;
        }

        // 发送私信窗口
        .send-card {

          .el-form {
            width: 80%;
            margin: 0 auto;
          }
        }

        // 私信目标
        .target-box {
          width: 70%;
          margin: 0 auto;
        }

        // 私信详情内容列表
        ul {
          width: 70%;

          li {
            // 私信会话容器
            .box-card-div {
              padding: 10px 30px;
            }
          }
        }
      }
    }

    .aside {
      float: left;
      width: 23%;
      height: 700px;
      border-radius: 4px;
      background: linear-gradient(to right, #e5e4e4, black);
    }
  }
}


// sm
@media screen and (max-width: 960px) {
  .user-message-letter-container {

    .container-in {
      clear: both;
      width: 100%;

      .main {
        width: 100%;
        margin: 0 auto;

        // 顶部大头像区
        .avatar-box {

          .el-icon-message-solid {
            padding-left: 30px;
            color: white;
          }

          .letter-a {
            padding-right: 30px;
            color: white;
          }
        }

        .letter-box {
          // 发送私信图标按钮
          .el-icon-edit-outline {
            float: right;
            margin: 0 10px 10px 0;
            font-size: 30px;
            box-shadow: 0 0 20px 6px white;
          }
        }

        ul {
          li {
            // 私信会话容器
            .box-card-div {
              padding: 10px;
            }
          }
        }
      }

      .aside {
        width: 100%;
      }
    }
  }
}
</style>
